"""
Compliance Item API 路由
提供合规项表的HTTP接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional, List
from uuid import UUID

from db.session import get_db
from schemas.complianceItem import (
    ComplianceItemCreate,
    ComplianceItemUpdate,
    ComplianceItemResponse,
    ComplianceItemPagination
)
from core import complianceItem as compliance_item_service
from log import log_api, log_error
from core import attachment as attachment_service
from schemas.attachment import AttachmentResponse

router = APIRouter(
    prefix="/compliance-items",
    tags=["compliance-items"],
    responses={404: {"description": "Compliance item not found"}},
)

@router.get("/", response_model=ComplianceItemPagination)
async def get_compliance_items(
    assessment_plan_id: Optional[UUID] = None,
    title: Optional[str] = None,
    compliance_type: Optional[str] = None,
    risk_level: Optional[str] = None,
    compliance_status: Optional[str] = None,
    progress_status: Optional[str] = None,
    inspector: Optional[str] = None,
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db)
) -> ComplianceItemPagination:
    """
    获取合规项列表，支持分页和过滤。
    
    Args:
        assessment_plan_id: 按评估计划ID过滤（可选）
        title: 按标题过滤（可选）
        compliance_type: 按合规类型过滤（可选）
        risk_level: 按风险级别过滤（可选）
        compliance_status: 按合规状态过滤（可选）
        progress_status: 按进度状态过滤（可选）
        inspector: 按检查人过滤（可选）
        skip: 跳过的记录数
        limit: 返回的最大记录数
        db: 数据库会话依赖
        
    Returns:
        分页合规项列表
    """
    log_api(f"Getting compliance items with filters: assessment_plan_id={assessment_plan_id}, title={title}, compliance_type={compliance_type}", 
           module="router.complianceItem")
    
    # 构建过滤条件
    filters = {}
    if assessment_plan_id:
        filters["assessment_plan_id"] = assessment_plan_id
    if title:
        filters["title"] = title
    if compliance_type:
        filters["compliance_type"] = compliance_type
    if risk_level:
        filters["risk_level"] = risk_level
    if compliance_status:
        filters["compliance_status"] = compliance_status
    if progress_status:
        filters["progress_status"] = progress_status
    if inspector:
        filters["inspector"] = inspector
    
    return await compliance_item_service.get_compliance_items(
        db=db, skip=skip, limit=limit, filters=filters
    )


@router.get("/{item_id}", response_model=ComplianceItemResponse)
async def get_compliance_item(
    item_id: UUID,
    db: AsyncSession = Depends(get_db)
) -> ComplianceItemResponse:
    """
    根据ID获取特定合规项。
    
    Args:
        item_id: 合规项ID
        db: 数据库会话依赖
        
    Returns:
        合规项详情
        
    Raises:
        HTTPException: 当合规项不存在时
    """
    log_api(f"Getting compliance item with ID: {item_id}", module="router.complianceItem")
    
    item = await compliance_item_service.get_compliance_item(db=db, item_id=item_id)
    if item is None:
        log_error(f"Compliance item with ID {item_id} not found", module="router.complianceItem")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Compliance item with ID {item_id} not found"
        )
        
    return item

@router.post("/", response_model=ComplianceItemResponse, status_code=status.HTTP_201_CREATED)
async def create_compliance_item(
    item: ComplianceItemCreate,
    db: AsyncSession = Depends(get_db)
) -> ComplianceItemResponse:
    """
    创建新的合规项。
    
    Args:
        item: 合规项数据
        db: 数据库会话依赖
        
    Returns:
        创建的合规项
        
    Raises:
        HTTPException: 当数据验证失败时
    """
    log_api(f"Creating compliance item: {item.title}", module="router.complianceItem")
    
    try:
        return await compliance_item_service.create_compliance_item(db=db, item_data=item)
    except ValueError as e:
        log_error(f"Failed to create compliance item: {str(e)}", module="router.complianceItem")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

@router.post("/bulk", response_model=List[ComplianceItemResponse], status_code=status.HTTP_201_CREATED)
async def bulk_create_compliance_items(
    items: List[ComplianceItemCreate],
    db: AsyncSession = Depends(get_db)
) -> List[ComplianceItemResponse]:
    """
    批量创建合规项。
    
    Args:
        items: 合规项数据列表
        db: 数据库会话依赖
        
    Returns:
        创建的合规项列表
        
    Raises:
        HTTPException: 当数据验证失败时
    """
    log_api(f"Bulk creating {len(items)} compliance items", module="router.complianceItem")
    
    try:
        return await compliance_item_service.bulk_create_compliance_items(db=db, items_data=items)
    except ValueError as e:
        log_error(f"Failed to bulk create compliance items: {str(e)}", module="router.complianceItem")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

@router.put("/{item_id}", response_model=ComplianceItemResponse)
async def update_compliance_item(
    item_id: UUID,
    item: ComplianceItemUpdate,
    db: AsyncSession = Depends(get_db)
) -> ComplianceItemResponse:
    """
    更新现有合规项。
    
    Args:
        item_id: 合规项ID
        item: 更新的合规项数据
        db: 数据库会话依赖
        
    Returns:
        更新后的合规项
        
    Raises:
        HTTPException: 当合规项不存在或数据验证失败时
    """
    log_api(f"Updating compliance item with ID: {item_id}", module="router.complianceItem")
    
    try:
        updated_item = await compliance_item_service.update_compliance_item(
            db=db, item_id=item_id, item_data=item
        )
        
        if updated_item is None:
            log_error(f"Compliance item with ID {item_id} not found for update", module="router.complianceItem")
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Compliance item with ID {item_id} not found"
            )
            
        return updated_item
    except ValueError as e:
        log_error(f"Failed to update compliance item: {str(e)}", module="router.complianceItem")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_compliance_item(
    item_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    删除合规项。
    
    Args:
        item_id: 合规项ID
        db: 数据库会话依赖
        
    Raises:
        HTTPException: 当合规项不存在时
    """
    log_api(f"Deleting compliance item with ID: {item_id}", module="router.complianceItem")
    
    success = await compliance_item_service.delete_compliance_item(db=db, item_id=item_id)
    
    if not success:
        log_error(f"Compliance item with ID {item_id} not found for deletion", module="router.complianceItem")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Compliance item with ID {item_id} not found"
        )
    
    # 204 No Content 响应不包含响应体

@router.get("/{compliance_item_id}/attachments", response_model=List[AttachmentResponse])
async def get_item_attachments(
    compliance_item_id: UUID,
    db: AsyncSession = Depends(get_db)
) -> List[AttachmentResponse]:
    """
    获取合规项的所有附件信息
    
    - **compliance_item_id**: 合规项ID
    
    返回:
        附件信息列表，包含id、name、type、size等信息
    """
    log_api(f"Getting attachments for compliance item ID: {compliance_item_id}", module="router.complianceItem")
    return await attachment_service.get_attachments(db, compliance_item_id)
